import {Collection} from "mongodb";
import {Promise} from 'es6-promise';

import {BaseModel} from "../core/base.model";
import {AggregateParam} from "../core/params";
import {CursorType} from "../core/defines";

export default class RegionModel extends BaseModel {
    constructor(coll: Collection) {
        super(coll);
    }

    getAllProvinces(): Promise<any>{
        let options = {value: '$id', name: 1, _id: 0};
        let param = new AggregateParam();
        param.push(CursorType.PROJECT, options);
        return this.aggregate(param);
    }

    getCitiesByProvinceId(id: number): Promise<any>{
        let match = {id: id};
        let project = { name: "$cities.name", value: "$cities.id", _id: 0 };
        let param = new AggregateParam();
        param.push(CursorType.UNWIND, "$cities");
        param.push(CursorType.MATCH, match);
        param.push(CursorType.PROJECT, project);

        return this.aggregate(param);
    }

    getDistrictsByCityId(id: number): Promise<any>{
        let match = { "cities.id": id };
        let project = { value: "$cities.districts.id", name: "$cities.districts.name", _id: 0 };
        let param = new AggregateParam();
        param.push(CursorType.UNWIND, "$cities");
        param.push(CursorType.MATCH, match);
        param.push(CursorType.UNWIND, "$cities.districts");
        param.push(CursorType.PROJECT, project);

        return this.aggregate(param);
    }

    name() { return 'RegionModel'; }
}
